<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>消息通知测试</title>
    <script src="./js/axios-0.18.0.js"></script>
    <script src="./js/vue.js"></script>
    <script src="./plugins/elementui/index.js"></script>
    <link rel="stylesheet" href="./css/style.css"/>
    <link rel="stylesheet" href="./plugins/elementui/index.css"/>
</head>
<body style="text-align: center">
    <div id="app">
        <el-badge :value="quantity" :max="99" class="item" style="margin-top: 200px;">
            <el-button icon="el-icon-bell" circle style="border: none" ></el-button>
        </el-badge>
    </div>
</body>
<script>
    // 页面关闭时调用此方法关闭websocket连接
    window.onbeforeunload = function (e) {
        axios.get('/netty/close')
        e.returnValue = ""
    }
    const vue = new Vue({
        el: '#app',
        data() {
            return {
                quantity: 0,
                socket: {}
            }
        },
        mounted() {
            // 获取DB中的未读消息数量
            this.getUnreadQuantity()
            // 初始化WebSocket
            this.initWebSocket()
        },
        methods: {
            initWebSocket() {
                if (!window.WebSocket) {
                    window.WebSocket = window.MozWebSocket;
                }
                if (window.WebSocket) {
                    console.log(this.socket)
                    this.socket = new WebSocket("ws://127.0.0.1:1234/ws");

                    let that = this
                    this.socket.onmessage = function (event) {
                        const sysData = JSON.parse(event.data).data.sysNoticeCount;
                        if (sysData) {
                            // mq中的新消息数量
                            that.quantity += parseInt(sysData)
                            // 将mq中的新消息保存到DB中
                            that.handleCacheUnread()
                        }
                    };
                    this.socket.onopen = function (event) {
                        that.socket.send('{}');
                    };
                    this.socket.onclose = function (event) {
                    };
                } else {
                    console.log("您的浏览器不支持WebSocket协议！")
                }
            },
            getUnreadQuantity() {
                axios.get('/notice/unread').then(res => {
                    if (res.data.result) {
                        this.quantity += res.data.data
                    }
                })
            },
            handleCacheUnread() {
                axios.get('/notice/cache')
            }
        }
    });
</script>
</html>